package com.nuanshui.heatedloan.userinfo.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.nuanshui.heatedloan.aliases.IdTypeHandler;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.constant.RabbitMqQueue;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageHandler;
import com.nuanshui.heatedloan.middleware.rabbitmq.annotation.MqMessageHandler;
import com.nuanshui.heatedloan.userinfo.facade.UserTokenService;
import com.nuanshui.heatedloan.userinfo.model.UserDeviceToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * deviceToken 保存的消息
 * @author GH
 *
 */
@MqMessageHandler(RabbitMqQueue.USER_TOKEN_SAVE_MSG)
public class TokenSaveMsgHandler implements RabbitmqMessageHandler {
	
	private Logger logger = LoggerFactory.getLogger(TokenSaveMsgHandler.class);
	
	@Autowired
	private UserTokenService userTokenService;
	@Override
	public void onMessage(Message message, Channel channel) throws Exception {
		try{
			LogUtil.info(logger, "-----------------------开始保存用户 token-----------------------");
			
			String msg = new String(message.getBody());
			JSONObject jObject =  JSON.parseObject(msg);
			String deviceToken = jObject.getString("deviceToken");
			String deviceType =  jObject.getString("deviceType");
			String userId = jObject.getString("userId");
			String version = jObject.getString("version");
			userTokenService.deleteByDeviceTokenAndDeviceType(deviceToken, deviceType);
			userTokenService.setUserIdNullByUserId(userId);
			// 说明存在这个token不存在
			UserDeviceToken userDeviceToken = new UserDeviceToken();
			userDeviceToken.setUserId(IdTypeHandler.decode(userId));
			userDeviceToken.setDeviceToken(deviceToken);
			userDeviceToken.setDeviceType(deviceType);
			userDeviceToken.setCreatedAt(new Date());
			userDeviceToken.setUpdatedAt(new Date());
			userDeviceToken.setVersion(version);
			userTokenService.addUserToken(userDeviceToken);
		    LogUtil.info(logger, "-----------------------结束保存用户 token-----------------------");
		    
		}catch(Exception e){
			
			LogUtil.error(logger, "-----------------------保存用户token失败！！！-----------------------", e);
			
		}
		channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
	}

}
